﻿
using MediatR;
using RBAC.Common.Domains;
using RBAC.Common.Dto;
using RBAC.Common.infrastructures.interfaces;
using RBAC.Enum;

namespace RBAC.api.Application.commond.RBAC
{
    public class RoleCreateHander : IRequestHandler<RoleCreateCommand, Rulst>
    {


        private readonly IbaseRpository<Role> _Role;

        private readonly IbaseRpository<RolePermission> _RolePermission;

        public RoleCreateHander(IbaseRpository<Role> role, IbaseRpository<RolePermission> rolePermission)
        {
            _Role = role;
            _RolePermission = rolePermission;
        }

        public async Task<Rulst> Handle(RoleCreateCommand request, CancellationToken cancellationToken)
        {
           
            var result= new Rulst() { Code=(int)Reult .success};


            var Roles = new Role()
            {

                RoleName = request.RoleName,
            };

            //角色新增
            var list=_Role.Add(Roles);


            var getRoleid=_Role.Query().Where(x=>x.RoleName==request.RoleName).FirstOrDefault();

            if(getRoleid!=null)
            {
                foreach (var role in request.PermissionList)
                {


                    var RolePermissions = new RolePermission()
                    {

                        Roleid = getRoleid.Roleid,
                        RolePermssionid = 0,
                        Permissionid = role
                    };

                    _RolePermission.Add(RolePermissions);

                    result.Code = (int)Reult.Addad;

                }
            }



            return result;
        }
    }
}
